# readnums.auk
# Tim Menzies
# Sept 12, 2012

"""

stuff

"""

@include "lib.awk"
@include "tile.awk"

function _readnums(f,  datas) {
  readnums(f ? f : "cat data/gots/knn/*.csv",datas)
  dumpnums(datas)
}
function readnums(com,datas,    \
                  data,rx,words,i,n,word,id,parts,mid) {
  com = com ? com : "cat -"
  data = rx = 0
  while ((com | getline) > 0) {
    gsub(/#.*/,"")
    if (/^[\t ]*$/) continue
    n = split($0,words,/[ \t\r\n]+/)
    for(i=1;i<=n;i++) {
      word = words[i]
      if (nump(word)) {
        readnum(datas,0   ,rx,++id,word)
        readnum(datas,data,rx,++id,word)
      }
      else 
        if (word) {
          split(word,parts,":")
          data = parts[1]
          rx   = parts[2] 
     }}}
    for(data in datas) {
      for(rx in datas[data]) {
        n = asort(datas[data][rx]["="],datas[data][rx]["="])
        mid = round(n/2)
        datas[data][rx]["med"] = datas[data][rx]["="][mid]
      }}
    for(data in datas) 
      asort(datas[data],datas[data],"medsort")
}
function medsort(k1,v1,k2,v2) {
  return v1["med"] - v2["med"]
}
function readnum(datas,data,rx,id,num) {
  datas[data][rx]["rx"] = rx
  read1num(datas[data][rx],id,num)
}
function read1num(a,id,num,   sum,n) {
        a["="][id] = num
  sum = a["s"]   += num
        a["s2"]  += num * num
  n = ++a["n"]
        a["mu"]   = sum/n
}
function dumpnums(datas,  data,rx,v,m,i,j,n,key,keys,chops) {
  m=s2l("id,rx,n,mu,s,s2,rank",keys)
  pairs("0.25,-,0.5,-,0.75,  ",chops)
  for(data in datas) {
    print "\n----| " data " |--------------------------------"
    n = length(datas[data])
    for(i=1;i<=n;i++)  {
      print ""
      for(j=1;j<=m;j++) {
        key=keys[j]
        if (key in datas[data][i])
          print data, i,key,datas[data][i][key]    
      }}}}
